package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.common.Result;
import com.example.entity.GreenHouse;
import com.example.entity.Sensors;
import com.example.mapper.SensorMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SensorService {

    @Resource
    private SensorMapper sensorMapper;

    public Result listSensors(GreenHouse greenHouse) {
        List<Sensors> sensorsList = sensorMapper.getSensorsListByGreenHouseId(greenHouse.getId());
        return Result.success(sensorsList);
    }

    public Result addSensors(List<Sensors> sensors) {
        for (Sensors sensor : sensors ){
            if(sensor.getStatus().getDesc().equals("离线")){
                Date date = DateUtil.date();
                sensor.setLastActive(date);
            }
            if(!sensorMapper.addSensor(sensor)){
                return Result.error("添加错误");
            }
        }
        return Result.success("添加成功",null);
    }

    public Result deleteSensors(List<Sensors> sensors) {
        List<Integer> idList = sensors.stream().map(Sensors::getId).collect(Collectors.toList());
        if(!sensorMapper.deleteByIdList(idList)){
            return Result.error("删除失败");
        }
        return Result.success("删除成功",null);
    }

    public Result updateSensors(List<Sensors> sensors) {
        for (Sensors sensor : sensors){
            if(sensor.getStatus().getDesc().equals("离线")){
                Date date = DateUtil.date();
                sensor.setLastActive(date);
            }
            if(!sensorMapper.updateSensor(sensor)){
                return Result.error("更新失败");
            }
        }
        return Result.success("更新成功");
    }

    public List<Sensors> getSensorsByGreenHouse(GreenHouse greenHouse){
        List<Sensors> sensorsList = new ArrayList<>();
        //获取对应大棚的传感器
        sensorsList = sensorMapper.getSensorsListByGreenHouseId(greenHouse.getId());
        //过滤、获取对应类型的传感器
        sensorsList = sensorsList.stream()
                .filter(x -> x.getType().equals(greenHouse.getType())).collect(Collectors.toList());
        return sensorsList;
    }

    public void deleteByGreenHouseId(Integer id) {
        sensorMapper.deleteByGreenHouseId(id);
    }
}
